<?php
namespace Application\Controller;

require_once __DIR__.'/../Resource/article/functions.php';

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class ArticleController extends AbstractActionController
{
    public function indexAction() {        
        $sProdId = $this->params()->fromRoute('id');
        if($sProdId == null) {
            // req == "/article-"
            header('Location: /');
            exit;
        }

        $iProdId = intval($sProdId);

        $oEm = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');

        $oRepoProduit = $oEm->getRepository('Application\Model\Entity\Produit');

        $oProduct = $oRepoProduit->findOneBy(array('id' => $iProdId));
        //si le produit n'existe pas
        if($oProduct == null) {
            return array('error' => "L'article demandé est introuvable :(");
        }

        //on récupère l'id de l'utilisateur
        $iUserId = null;
        
        $oAuth = $this->getServiceLocator()->get('zfcuser_auth_service');
        if($oAuth->hasIdentity()) {
            $oUser = $oAuth->getIdentity();

            $iUserId = $oUser->getId();
        }
        
        //gestion des actions
        switch($oProduct->getEtat()->getId()) {
            case 1: //"En vente"
                $sBuy = $this->params()->fromPost('buy');

                if($sBuy != null) {
                    header('Content-type: application/json');

                    if($iUserId !== null) {
                        $aBuyRet = Buy($oEm, $iUserId, $iProdId);

                        die(json_encode(array('success' => 1, 'values' => $aBuyRet)));
                    } else {
                        die(json_encode(array('error' => 'not_authenticated')));
                    }
                }
                break;
            case 2: //"En enchère"
                //si une action enchère est soumise
                $sBid = $this->getRequest()->getPost('bid');
                if($sBid != null) {
                    header('Content-type: application/json');

                    if($iUserId !== null) {
                        $aBidRet = Bid($oEm, $iUserId, $oProduct, floatval($sBid));

                        if(isset($aBidRet['error'])) {
                            die(json_encode(array('error' => $aBidRet['error'])));
                        }

                        die(json_encode(array('success' => 1, 'values' => $aBidRet)));
                    } else {
                        die(json_encode(array('error' => 'not_authenticated')));
                    }
                }
                break;
            case 3: //"Vendu"
                //pas d'actions possibles
                break;
        }
        
        //
        $this->view = new ViewModel();

        $this->view->setVariables(array(
            'userid' => $iUserId,
        ));

        switch($oProduct->getEtat()->getId()) {
            case 2: //"En enchère"
                $aLatestBid = GetLatestBid($oEm, $iProdId);
                if (!empty($aLatestBid)) {
                    $this->view->setVariables(array(
                      'e_montant' => $aLatestBid['montant'],
                      'e_uid' => $aLatestBid['userid'],
                      'e_nom' => $aLatestBid['prenom'].' '.$aLatestBid['nom']
                    ));
                }
                break;
            case 3: //"Vendu"
                /*
                $oProduitVendu = $oEm->find('Application\Model\Entity\ProduitVendu', $iProdId);
                var_dump($oProduitVendu);
                $this->view->p_datevente=$oProduitVendu->getDateVente();
                */
        }

        $moduleConfig = $this->getServiceLocator()->get('config');
        $file_path = $moduleConfig['application']['file_path'];
        $full_file_path = $moduleConfig['application']['full_file_path'];

        $oRepoUtilisateur = $oEm->getRepository('Application\Model\Entity\Utilisateur');

        $oQuery = $oRepoUtilisateur->createQueryBuilder('u')
            ->where('u.boutique = :boutiqueid')
            ->setParameter('boutiqueid', $oProduct->getBoutique()->getId())
            ->getQuery();

        $iProdUserId = $oQuery->getSingleResult()->getId();

        $this->view->setVariables(array(
           'p_libelle' => $oProduct->getLibelle(),
           'p_description' => $oProduct->getDescription(),
           'p_taille' => $oProduct->getTaille(),
           'p_prix' => $oProduct->getPrix(),
           'p_datefin' => $oProduct->getDateFin(),
           'p_etat' => $oProduct->getEtat()->getId(),
           'p_images' => $oProduct->getImages(),
           'file_path' => $file_path,
           'full_file_path' => $full_file_path,
           'p_userid' => $iProdUserId,
	   'p_boutique' => $oProduct->getBoutique()->getId(),
        ));

	return $this->view;
    }
}

